package com.chen.assist;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

// 6辆车抢3个车位
public class SemaphoreTest {
    public static void main(String[] args) {

        // 3个线程，代表3个车位，限流
        Semaphore semaphore = new Semaphore(3);

        // 六个线程，代表六辆车
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "获得了车位");
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "离开了车位");
                }
            }, String.valueOf(i)).start();
        }

    }
}
